angular.module("UranusWei").factory('commonFactory', ["$http", "CacheFactory", '$rootScope', '$location', '$window', '$compile', '$timeout', '$interval', 'uranusPlus', 'appconfig', 'uranusiscroll', '$q', function ($http, CacheFactory, $rootScope, $location, $window, $compile, $timeout, $interval, uranusPlus, appconfig, uranusiscroll, $q) {
    $rootScope.headerOpacityTimeout = null;
    $rootScope.version = window.version;
    /*跳转站外链接*/
    $rootScope.othergo = function (path, title) {
        if (path) {
            if (path.startWith("http")) {
                if (uranusPlus.isApp && plus) {
                    plus.runtime.openURL(path);
                } else {
                    window.location.href = path;
                }
            } else {
                publicmethod.go(path);
            }
        }
    }
    $rootScope.toUpdate=function(){
        window.location.reload()
    }
    ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {//判断微信
        $rootScope.wxua = true
    }
    // 获取本地 url
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPaht = curWwwPath.substring(0, pos);
    // var localhostPaht="https://api.youlijinfu.com"
    appconfig.baseurladd = localhostPaht;
    // 默认图片地址
    $rootScope.imgbaseurl = appconfig.imgurl;
    //设备宽高
    $rootScope.deviceInfo = {
        width: parseInt($window.innerWidth),
        height: parseInt($window.innerHeight)
    }
    pointman.use('do', function () {
        var afs = pointman.getConfig();
        var afs_appkey = afs.appkey;
        var afs_scene = afs.scene;
        $rootScope.afs_token = afs.token;
        // console.log($rootScope.afs_token)
        // console.log('afs_scene: ' + afs_scene);
    });
    //同盾弹框关闭
    $rootScope.closetd = function () { publicmethod.messageclose(); }
    $rootScope.djsArr = [];/*保存页面所有定时器*/
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        $rootScope.Template.slideopeacity = false;
        $rootScope.previousState = fromState; /*记录上一个页面的信息*/
        publicmethod.messageclose();/* 打开新页面关闭其他的弹层 */
        setTimeout(function () {
            /*每次跳转页面之前关闭其他的定时器*/
            while ($rootScope.djsArr.length > 0) {
                $interval.cancel($rootScope.djsArr[0]);
                $timeout.cancel($rootScope.djsArr[0]);
                clearInterval($rootScope.djsArr[0]);
                clearTimeout($rootScope.djsArr[0]);
                publicmethod.removeArr($rootScope.djsArr, $rootScope.djsArr[0]);
            }
        }, 1);
    });
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
    });
    $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
        if (error.status == 0) {
            // console.log('An error occurred while changing states: ' + error);
            //publicmethod.messageshow("网络出现异常");
        }
    });
    $rootScope.tios = function () {
        return publicmethod.versions.ios
    };
    //下载APP事件
    $rootScope.GuidDown = function () {
        publicmethod.versions.android ? window.location.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.youlijinfu.android" : window.location.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.youlijinfu.android"
    };
    $rootScope.closeguiddown = function () {
        $rootScope.isGuidDown = false;
    }
    $rootScope.isGuidDown = true;
    $rootScope.backs = [];
    var isanimate = false; //是否有动画
    /* 加动画的 */
    function parentelement(type) {
        if (isanimate) {
            if (type == "back") {
                if (appconfig.baseanimateelement.hasClass("right")) {
                    appconfig.baseanimateelement.removeClass("right").addClass("left");
                }
            } else {
                if (appconfig.baseanimateelement.hasClass("left")) {
                    appconfig.baseanimateelement.removeClass("left").addClass("right");
                }
            }
        }
    }

    var publicmethod = {
        sub: function (arg1, arg2) {//浮点数减法
            var r1, r2, m, n;
            try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
            try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
            m = Math.pow(10, Math.max(r1, r2));
            //动态控制精度长度
            n = (r1 >= r2) ? r1 : r2;
            return ((arg1 * m - arg2 * m) / m).toFixed(n);
        },
        subc: function (arg1, arg2) {//浮点数乘法
            var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
            try { m += s1.split(".")[1].length } catch (e) { }
            try { m += s2.split(".")[1].length } catch (e) { }
            return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
        },
        getResult: function () {
            return this.result;
        },
        setResult: function (res) {
            this.result = res;
        },
        setBackLink: function (backurl, backedurls) {
            var isIndexOf = false;
            if ($rootScope.previousState) {//上一个访问状态。
                angular.forEach(backedurls, function (item, i) {
                    if ($rootScope.previousState.url.indexOf(item) > -1) {
                        isIndexOf = true;
                    };
                });
            }
            if (!$rootScope.previousState || isIndexOf) {
                $rootScope.Template.backlink = backurl;
                var path = angular.copy($location.$$path.toLowerCase());
                $rootScope.backs.push({ path: path, backurl: backurl });
            }
        },
        inputBlur: function () {
            var input = document.getElementsByTagName("input");
            for (var i = 0; i < input.length; i++) {
                if (/(text|tel|number|password|email)/.test(input[i].type)) {
                    input[i].blur();
                }
            }
        },
        ajaxStore: function (opption) {
            if (opption) {
                var isLoading = true;
                if (opption.storekey && opption.callback) {
                    if (opption.setExpires) {
                        opption.storekey = "time_" + opption.storekey;
                    }
                    var storevalue = CacheFactory.getStorage(opption.storekey);
                    if (storevalue) {
                        isLoading = false;
                        opption.callback(storevalue);
                    }
                }
                if (isLoading) {
                    publicmethod.messageloading({ process: true });
                    // dthload.lodingBegin();
                }
                publicmethod.ajax(opption.url, opption.data, function (result) {
                    if (result.code == 1) {
                        CacheFactory.setStorage(opption.storekey, result, opption.setExpires);
                    }
                    opption.callbacktwo(result);
                }, opption.err, opption.method);
            }
        },
        ajax: function (url, data, callback, err, method) {
            if (typeof callback != "function") {
                callback = data;
                data = {};
            }            
            if (data.u_id) {
                data.u_id = data.u_id;
                torequest()
            } else {
                data.u_id = CacheFactory.getUID();//'660c609f81ce480c989237e97801cc59';
                if (!data.u_id) {
                    var getcount = 0;
                    var idinterval = $interval(function () {
                        data.u_id = CacheFactory.getUID()
                        getcount++;
                        if (data.u_id || getcount > 10) {
                            torequest()
                            $interval.cancel(idinterval)
                        }
                    }, 50)
                } else {
                    torequest()
                }

            }

            /*data.sourceTypeId = CacheFactory.getSourceTypeId();*/
            function torequest() {
                data.sourceTypeId = getMySourceTypeId();
                data.terminal = "wei";
                var isapp = CacheFactory.getH5Storage("isapp");
                /* 是否 App 2 */
                if (isapp == "2") {
                    if (uranusPlus.isApp) {
                        if (uranusPlus.isIos()) {
                            data.terminal = "ios";
                        } else if (uranusPlus.isAndroid()) {
                            data.terminal = "android";
                        }
                    }
                }
                if (!url.startWith("http")) {
                    url = appconfig.baseurl + url;
                }
                if (method == "post") {
                    var d = "";
                    angular.forEach(data, function (value, key) {
                        if (d) {
                            d = d + "&";
                        }
                        d = d + key + "=" + value;
                    })
                    $http({
                        url: url,
                        method: "POST",
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        data: d,
                        timeout: 60 * 1000,
                    }).success(callback).error(function () {
                        if (typeof err == "function") {
                            err({ code: -1, data: '请求失败，请稍后再试' });
                        }
                    });
                } else if (appconfig.isjsonp) {
                    data.jsonp = "true";
                    data.callback = "JSON_CALLBACK";
                    $http.jsonp(url, { params: data }).success(callback).error(function () {
                        if (typeof err == "function") {
                            err({ code: -1, data: '请求失败，请稍后再试' });
                        }
                    });
                } else {
                    $http.get(url, { params: data }).success(callback).error(function () {
                        if (typeof err == "function") {
                            err({ code: -1, data: '请求失败，请稍后再试' });
                        }
                    });
                }
            }

        },
        ajaxPromise: function (url, data, method) {

            data.u_id = CacheFactory.getUID();//'660c609f81ce480c989237e97801cc59';
            /*data.sourceTypeId = CacheFactory.getSourceTypeId();*/
            data.sourceTypeId = getMySourceTypeId();
            data.terminal = "wei";
            var isapp = CacheFactory.getH5Storage("isapp");
            /* 是否 App 2 */
            if (isapp == "2") {
                if (uranusPlus.isApp) {
                    if (uranusPlus.isIos()) {
                        data.terminal = "ios";
                    } else if (uranusPlus.isAndroid()) {
                        data.terminal = "android";
                    }
                }
            }
            if (!url.startWith("http")) {
                url = appconfig.baseurl + url;
            }

            var deferred = $q.defer();
            var promise = deferred.promise;
            if (method == "post") {
                var d = "";
                angular.forEach(data, function (value, key) {
                    if (d) {
                        d = d + "&";
                    }
                    d = d + key + "=" + value;
                });
                $http({
                    url: url,
                    method: "POST",
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    data: d,
                    timeout: 60 * 1000,
                }).success(function (data) {
                    if (data.code == 1) {
                        deferred.resolve(data);
                    } else {
                        deferred.reject(data);
                    }
                }).error(function (error) {
                    deferred.reject(error);
                });
            } else if (appconfig.isjsonp) {
                data.jsonp = "true";
                data.callback = "JSON_CALLBACK";
                $http.jsonp(url, { params: data }).success(function (data) {
                    if (data.code == 1) {
                        deferred.resolve(data);
                    } else {
                        deferred.reject(data);
                    }
                }).error(function (error) {
                    deferred.reject(error);
                });
            } else {
                $http.get(url, { params: data }).success(function (data) {
                    if (data.code == 1) {
                        deferred.resolve(data);
                    } else {
                        deferred.reject(data);
                    }
                }).error(function (error) {
                    deferred.reject(error);
                });
            }
            return promise;
        },
        removeArr: function (arr, info) {
            var index = arr.indexOf(info);
            if (index > -1) {
                arr.splice(index, 1);
            }
        },
        gologin: function () {  //掉线或者未登录跳转登录页面
            var user = CacheFactory.getUser();
            var uname = "";
            if (user) {
                uname = user.UserName;
            }
            CacheFactory.removestorage("user"); //清除用户信息 
            var currentPath = $window.location.pathname;
            if (currentPath != "/login/index") {
                publicmethod.go("/login/index?cp=" + currentPath + "&uname=" + uname);
            }
        },
        loginout: function (callback) {/* 退出登录 */
            var user = CacheFactory.getUser();
            var client = localStorage.getItem('clientId');
            var uname = "";
            if (user) {
                uname = user.UserName;
            }
            CacheFactory.removestorage("realnameinfo");
            publicmethod.ajax("/api/User/LoginOut", { clientId: client }, function (result) {
                CacheFactory.removestorage("user");
            }, function () {
            }, "post");
            $timeout(function () {
                publicmethod.go("/login/index?uname=" + uname + "&backurl=/main/center");
            }, 100);
        },
        GetRandomNum: function (Min, Max) {
            var Range = Max - Min;
            var Rand = Math.random();
            return (Min + Math.round(Rand * Range));
        },
        /*随机获取下拉刷新广告*/
        GetRandomPullAd: function () {
            return appconfig.refreshad.title[publicmethod.GetRandomNum(0, appconfig.refreshad.title.length - 1)];
        },
        /* 比较两个对象值是否相等 */
        isObjectValueEqual: function (a, b) {
            if (a == b) {
                return true;
            }
            if (!a || !b) {
                return false;
            }
            var aProps = Object.getOwnPropertyNames(a);
            var bProps = Object.getOwnPropertyNames(b);
            for (var i = 0; i < aProps.length; i++) {
                var propName = aProps[i];
                if (propName == "$$hashKey") {
                    continue;
                }
                if (a[propName] !== b[propName]) {
                    return false;
                }
            }
            return true;
        },
        /* 比较两个list值是否相等 */
        comparisonobj: function (a, b, callback) {
            var iscomparp = false;
            if (publicmethod.isArray(a) && publicmethod.isArray(b)) {
                if (a.length == b.length) {
                    for (var i = 0; i < a.length; i++) {
                        if (!publicmethod.isObjectValueEqual(a[i], b[i])) {
                            iscomparp = false;
                            break;
                        } else {
                            iscomparp = true;
                        }
                    }
                }
            }
            return iscomparp;
        },
        /* 是否是一个数组 */
        isArray: function (obj) {
            return Object.prototype.toString.call(obj) === '[object Array]';
        },
        /* 是否是一个对象 */
        isObject: function (obj) {
            return Object.prototype.toString.call(obj) === '[object Object]';
        },
        /* 跳转 */
        go: function (path) {
            if (path === 'back') { // Allow a 'back' keyword to go to previous pageX
                var back, curIndex = -1;
                angular.forEach($rootScope.backs, function (item, i) {
                    if (item.path == $location.$$path.toLowerCase()) {
                        $rootScope.Template.backlink = item.backurl;
                        return;
                    }
                });

                angular.forEach($rootScope.backs, function (item, i) {
                    if (item.path == $location.$$path.toLowerCase()) {
                        curIndex = i;
                        return;
                    }
                });
                if (curIndex > -1) {
                    $rootScope.backs.splice(curIndex, 1);
                }
                if ($rootScope.Template.backlink) {
                    parentelement("back");
                    $location.url($rootScope.Template.backlink);
                } else {
                    parentelement("go");
                    $window.history.back();
                }
            }
            else { // Go to the specified path
                parentelement("go");
                $location.url(path);
            }
        },
        newGuid: function () {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    guid += "";
            }
            return guid;
        },
        versions: function () {
            var u = navigator.userAgent.toLowerCase(), app = navigator.appVersion;
            return {
                trident: u.indexOf('trident') > -1, //IE内核
                presto: u.indexOf('presto') > -1, //opera内核
                webKit: u.indexOf('applewebkit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('gecko') > -1 && u.indexOf('khtml') == -1,//火狐内核
                mobile: !!u.match(/applewebkit.*mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i), //ios终端
                android: u.indexOf('android') > -1 || u.indexOf('linux') > -1, //android终端或者uc浏览器
                iPhone: u.indexOf('iphone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('ipad') > -1, //是否iPad
                webApp: u.indexOf('safari') == -1, //是否web应该程序，没有头部与底部
                pad: u.indexOf("pad") > -1,
                wx: u.indexOf("micromessenger") > -1
            };
        }(),
        /* 加载完成事件,包括超时也会进入事件 */
        initComplate: function (list, count, callback) {
            var myinterval = setInterval(function () {
                if (list.length >= count) {
                    callback();
                    clearInterval(myinterval);
                }
            }, 500);
        },
        /* 弹框提示 */
        messageshow: function (ops) {
            if (ops) {
                if (Object.prototype.toString.call(ops) != '[object Object]') {
                    ops = {
                        content: ops
                    }
                }
            }
            /* 如果有标题，默认黑层点击不关闭 */
            ops.shadeClose = ops.shadeClose == undefined ? (ops.title ? false : true) : ops.shadeClose === true ? true : false;

            if (ops.title && ops.content) {
                layer.open({
                    title: [
                        ops.title,
                        appconfig.messagetitlestyle
                    ],
                    shade: false,
                    // shadeClose: ops.shadeClose,
                    content: ops.content,
                    index: ops.index,
                    time: ops.time || appconfig.messagetime
                });
            } else if (ops.content) {
                layer.open({
                    content: ops.content,
                    style: appconfig.messagecontentstyle,
                    shade: false,
                    // shadeClose: ops.shadeClose,
                    time: ops.time || appconfig.messagetime,
                    index: ops.index
                });
            }
        },
        /*按钮提示 可选择输入按钮名称*/
        messagebutton: function (content, btncontent, callback) {
            if (content) {
                layer.open({
                    content: content,
                    btn: [btncontent ? btncontent : 'OK'],
                    shadeClose: false,
                    yes: function () {
                        layer.closeAll();
                        if (callback) {
                            callback();
                        }
                    }
                })
            }
        },
        /*关闭所有提示层*/
        messageclose: function (ops) {
            if (ops && ops.index) {
                layer.close(ops.index);
            } else {
                if (layer) {
                    layer.closeAll();
                }
            }
            if (privatemethod.isLoding == true) {
                privatemethod.isLoding = false;
                privatemethod.div_process.style.width = "100%";
                privatemethod.currdom = 100;
                var currInterval = 1;
                var endLodingInterval = setInterval(function () {
                    if (currInterval <= 0) {
                        privatemethod.div_process.style.width = "0%";
                        clearInterval(endLodingInterval);
                        return;
                    }
                    currInterval -= 0.1;
                    privatemethod.div_process.style.opacity = currInterval;
                }, 100);
            }
        },
        /* loading加载 */
        messageloading: function (ops) {
            if (ops && ops.process) {
                ops.shade = false;        //是否显示加载层的遮蔽层
                if (privatemethod.currdom == 100) {
                    privatemethod.isLoding = true;
                    privatemethod.currdom = 0;
                    privatemethod.div_process.style.opacity = 1;
                    privatemethod.loadingHandler(1, 95, privatemethod.div_process);
                }
            }
            var defaultops = {
                type: 2,
                time: 60,  //60秒自动关闭
                index: 999
            };
            privatemethod.extend(defaultops, ops);
            if (layer) {
                layer.open(defaultops);
            }
        },
        /*生成遮罩*/
        messageview: function (html, ops, scope) {

            if (ops) {
                if (!ops.bgcolor) {
                    ops.bgcolor = "#f2f2f2";
                }
                if (ops.shade === undefined) {
                    ops.shade = true;
                }
            } else {
                ops = {};
            }
            ops.shadeClose = ops.shadeClose == undefined ? (ops.title ? false : true) : ops.shadeClose === true ? false : true;
            layer.open({
                shade: ops.shade,
                type: 1,
                shadeClose: ops.shadeClose,
                time: ops.time,
                title: ops.title,
                content: html,
                style: ops.width && ops.height ? 'width:' + ops.width + '; height:' + ops.height + '; background-color:' + ops.bgcolor + '; border:none; border-radius:5px;' : appconfig.messagepanlstyle
            });
            if (scope) {
                /*动态编译html*/
                var la = document.querySelector(".layermcont");
                if (la) {
                    setTimeout(function () {
                        $compile(la)(scope);
                    }, 20);
                }
            }
        },
        showYin: function (scope, timecash) {
            var html = "";
            html += '<div class="cys_tanchw">';
            html += '    <div class="cys_t_titw text_center" ng-click="closewindow()">';
            html += '         提示';
            html += '    </div>';
            html += '     <div class="cys_t_conw cys_t_c_w">';
            html += '         <div class="cys_t_c_s_w text-leftw">';
            html += '          亲，由于监管合规要求“用户充值后不可直接提现”。您账中的<font>' + timecash + '</font>元需要购买一次理财后才可提现，现在就去赚钱吧！'
            html += '         </div>';
            html += '         <div class="cys_iknow" ng-click="closewindow()">我知道了</div>';
            html += '    </div>';
            html += '</div>';
            publicmethod.messageclose()
            publicmethod.messageview(html, { width: 1, height: 1 }, scope);
        },
        showTD: function (scope) {
            var html = "";
            html += '<div class="td_bg">';
            html += '     <span class="td_close" activeclass="nobgm" ng-click="closetd()" >';
            html += '    </span>';
            html += '</div>';
            publicmethod.messageclose()
            publicmethod.messageview(html, { width: 1, height: 1 }, scope);
        },
        showHB: function (scope) {
            var html = "";
            html += '<div class="hb_tan">';
            html += '   <div class="hb_header">';
            html += '          按比例激活红包   ';
            html += '   </div>';
            html += '   <div class="hb_tan">';
            html += '     <img src="../../images/mine/hbbl_06.png">';
            html += '       <span ng-click="goRedBag()">激活红包</span>';
            html += '   </div>';
            html += '</div>';
            publicmethod.messageclose()
            publicmethod.messageview(html, { width: 1, height: 1 }, scope);
        },
        showHBM: function (scope) {
            var html = "";
            html += '<div class="hb_tan">';
            html += '   <div class="hb_header">';
            html += '          满额激活红包   ';
            html += '   </div>';
            html += '   <div class="hb_tan">';
            html += '     <img src="../../images/mine/hbme_03.png">';
            html += '       <span ng-click="goRedBag()">激活红包</span>';
            html += '   </div>';
            html += '</div>';
            publicmethod.messageclose()
            publicmethod.messageview(html, { width: 1, height: 1 }, scope);
        },
        /* 更新transform */
        updateTransform: function (obj, css) {
            obj.css("-webkit-transform", css);
            obj.css("-moz-transform", css);
            obj.css("-o-transform", css);
            obj.css("transform", css);
        },
        /* 更新updateTransition */
        updateTransition: function (obj, css) {
            obj.css("-o-transition", css);
            obj.css("-moz-transition", css);
            obj.css("-webkit-transition", css);
            obj.css("transition", css);
        },
        messagephotos: function (imglist, ops, scope) {
            var windowheight = window.innerHeight, windowwidth = window.innerWidth;
            var that = this;
            var imghtml = "";
            var phtml = "";
            var bothtml = "";
            var closehtml = "<div class=\"layermend js_close_layermend\" style=\" z-index:999;left:" + (windowwidth - 40) + "px; \"></div>";
            var prevhtml = "";
            var nexthtml = "";
            if (!that.versions.mobile) {
                var dirTop = (windowheight / 2 - 25);
                prevhtml = "<div class=\"js_photo_prev\" style=\"position: fixed; left: 10px; float: left; top: " + dirTop + "px;z-index:99; \"><img src='https://file.youlijinfu.com/images/three_but_left.png' /></div>";
                nexthtml = "<div class=\"js_photo_next\" style=\"position: fixed; left: " + (windowwidth - 60) + "px; float: left; top: " + dirTop + "px;z-index:99; \"><img src='https://file.youlijinfu.com/images/three_but_right.png' /></div>";
            }
            var parentdom = null;
            var adTouch = {
                currentIndex: 0,
                startPos: {},
                movePos: {},
                cardMove: 0,
                loop: false,//  //是否循环轮播, 手机上暂时没有实现循环，pc上面循环的不好。 需要优化，如果有需求
                prevPos: null,
                js_photo_prev: null,
                js_photo_next: null,
                touchmoveNum: 0,
                gomove: true, //这个用来标识冒泡阻止事件的问题
                showhidedirection: function () {//计算方向 
                    if (!that.versions.mobile) {
                        if (!adTouch.loop && (adTouch.currentIndex == 0)) {
                            adTouch.js_photo_prev.style.display = "none";
                        } else if (!adTouch.loop && (adTouch.currentIndex == imglist.length - 1)) {
                            adTouch.js_photo_next.style.display = "none";
                        } else {
                            adTouch.js_photo_prev.style.display = "block";
                            adTouch.js_photo_next.style.display = "block";
                        }
                    }
                },
                touchstart: function () {
                    adTouch.gomove = false;
                    var touch = event.targetTouches[0]; //touches数组对象获得屏幕上所有的touch，取第一个touch
                    adTouch.startPos = { x: touch.pageX, y: touch.pageY }; //取第一个touch的坐标值 
                    that.updateTransition(angular.element(parentdom), "none");
                },
                touchmove: function () {
                    adTouch.gomove = true;
                    var touch = event.targetTouches[0];
                    adTouch.movePos = { x: touch.pageX - adTouch.startPos.x, y: touch.pageY - adTouch.startPos.y }; //取第一个touch的坐标值 
                    if (adTouch.prevPos != null) {
                        adTouch.cardMove -= (adTouch.prevPos.x - adTouch.movePos.x) / 1.5;
                    } else {
                        adTouch.cardMove += adTouch.movePos.x / 1.5;
                    }
                    that.updateTransform(angular.element(parentdom), "translate3d(" + (adTouch.touchmoveNum + adTouch.cardMove) + "px,0px,0px)");
                    adTouch.prevPos = adTouch.movePos;
                    if (event.preventDefault) {
                        event.preventDefault();
                    }
                    else {
                        event.returnValue = false;
                    }
                },
                touchend: function (direction) {
                    if (!adTouch.gomove) {
                        return;
                    }
                    if (imglist.length > 1) {
                        //PC兼容左右切换 
                        if (direction == 1) {
                            if (adTouch.loop || adTouch.currentIndex < imglist.length - 1) {
                                adTouch.currentIndex++;
                            }
                        } else if (direction == -1) {
                            if (adTouch.loop || adTouch.currentIndex > 0) {
                                adTouch.currentIndex--;
                            }
                        } else {
                            if (adTouch.loop || adTouch.movePos.x < 0) {	//向左滑动
                                if (adTouch.currentIndex < imglist.length - 1) {
                                    if (adTouch.movePos.x < -80) {
                                        adTouch.currentIndex++;
                                    }
                                }
                            } else {
                                if (adTouch.loop || adTouch.currentIndex > 0) {
                                    if (adTouch.movePos.x > 80) {
                                        adTouch.currentIndex--;
                                    }
                                }
                            }
                        }
                    }
                    // var times = 0;
                    //无限循环
                    if (adTouch.loop) {
                        if (adTouch.currentIndex > imglist.length - 1) {
                            that.updateTransition(angular.element(parentdom), "none");
                            adTouch.currentIndex = 0;
                            adTouch.touchmoveNum = -(windowwidth * (imglist.length - 1));
                            that.updateTransform(angular.element(parentdom), "translate3d(" + adTouch.touchmoveNum + "px,0px,0px)");
                            // times = 1;
                        } else if (adTouch.currentIndex < 0) {
                            that.updateTransition(angular.element(parentdom), "none");
                            adTouch.currentIndex = imglist.length - 1;
                            adTouch.touchmoveNum = -(windowwidth * (imglist.length - 1));
                            that.updateTransform(angular.element(parentdom), "translate3d(" + adTouch.touchmoveNum + "px,0px,0px)");
                            // times = 1;
                        }
                    }
                    adTouch.touchmoveNum = - (adTouch.currentIndex * windowwidth);
                    // $timeout(function () {
                    that.updateTransition(angular.element(parentdom), "all 0.3s ease");
                    that.updateTransform(angular.element(parentdom), "translate3d(" + adTouch.touchmoveNum + "px,0px,0px)");
                    js_bottom_page.innerHTML = (adTouch.currentIndex + 1) + "/" + imglist.length;
                    adTouch.prevPos = null;
                    adTouch.cardMove = 0;
                    // }, times);
                }
            };
            var angular_body = angular.element(document.getElementsByTagName("body")[0]);
            var imglayouheight = ($rootScope.deviceInfo.height);
            if (angular_body.hasClass("immerse")) {
                imglayouheight = imglayouheight + 20;
            }
            for (var i = 0; i < imglist.length; i++) {
                imglist[i].setAttribute("pindex", i);
                imghtml += "<div style=\"display:inline-block;width:" + (windowwidth) + "px;height:" + (imglayouheight - 20) + "px;line-height:" + (imglayouheight - 20) + "px;\"><img class=\"js_init_img\" src=\"" + imglist[i].getAttribute("src") + "\"/></div>";

                imglist[i].addEventListener("click", function (e) {
                    e.stopPropagation();
                    var pindex = parseInt(this.getAttribute("pindex"));
                    adTouch.currentIndex = pindex;
                    adTouch.touchmoveNum = -(adTouch.currentIndex) * windowwidth;
                    showphotos();
                });
            }

            function showphotos() {
                phtml = "<div class=\"js_parentdom\" style=\"width:" + (windowwidth * imglist.length) + "px;  -webkit-transform: translate3d(" + (adTouch.touchmoveNum) + "px,0px,0px);\" >";
                bothtml = "<div id=\"js_bottom_page\" style='position:absolute;bottom:10px;width:" + (windowwidth) + "px;height:20px;color:#fff;'>" + (adTouch.currentIndex + 1) + "/" + (imglist.length) + "</div >";
                var html = closehtml + prevhtml + phtml + imghtml + "</div>" + bothtml + nexthtml;
                ops.height = "100%";
                ops.bgcolor = " rgba(0,0,0,0);";
                ops.width = "100%";
                publicmethod.messageview(html, ops, scope);

                var js_bottom_page = document.querySelector("#js_bottom_page");

                adTouch.js_photo_prev = document.querySelector(".js_photo_prev");
                adTouch.js_photo_next = document.querySelector(".js_photo_next");
                adTouch.showhidedirection();
                if (adTouch.js_photo_prev) {
                    angular.element(adTouch.js_photo_prev).on("click", function () {
                        event.stopPropagation();
                        adTouch.touchend(-1);
                        adTouch.showhidedirection();
                    });
                }
                if (adTouch.js_photo_next) {
                    angular.element(adTouch.js_photo_next).on("click", function () {
                        event.stopPropagation();
                        adTouch.touchend(1);
                        adTouch.showhidedirection();
                    });
                }
                $timeout(function () {
                    parentdom = document.querySelector(".js_parentdom");
                    if (ops.shadeClose) {
                        var layermanim = document.querySelector(".layermanim");
                        if (layermanim) {
                            angular.element(layermanim).on("click", function (event) {
                                event.stopPropagation();
                                parentdom = null;
                                that.messageclose();
                            });
                        }
                    }
                    if (parentdom) {
                        angular.element(parentdom).on("touchstart", adTouch.touchstart);
                        angular.element(parentdom).on("touchmove", adTouch.touchmove);
                        angular.element(parentdom).on("touchend", adTouch.touchend);
                    }
                    //增加点击黑色层关闭弹框
                    var js_close_laymshade = document.querySelector(".js_parentdom");
                    var js_close_layermend = document.querySelector(".js_close_layermend");
                    js_close_laymshade.onclick = js_close_layermend.onclick = function (event) {
                        event.stopPropagation();
                        parentdom = null;
                        that.messageclose();
                    };
                    js_close_layermend.ontouchmove = function () {
                        event.stopPropagation();
                        parentdom = null;
                        that.messageclose();
                    };
                }, 300);
            }
        },
        /* 上下啦隐藏顶部导航 */
        slideopeacity: function (uranusiscroll, curPath) {
            $timeout(function () {
                var positionY = uranusiscroll.y;//Math.abs(uranusiscroll.y);   
                var opacity = 0;
                if (positionY < -30) {
                    var positionYAbs = Math.abs(positionY);
                    if (positionYAbs >= 60) {
                        opacity = 1;
                    } else {
                        opacity = parseFloat(positionYAbs / 50).toFixed(1);
                        opacity = opacity > 1 ? 1 : opacity;
                    }
                } else {
                    if (location.pathname.toLowerCase() != curPath.toLowerCase()) {
                        opacity = 1;
                    } else {
                        opacity = 0;
                    }
                }
                $rootScope.Template.opacity = opacity;
            }, 0);
        },
        uniqueArr: function (collection, keyname) {
            var authArr = [], authKeys = [];
            if (collection && collection.length > 0) {
                angular.forEach(collection, function (item) {
                    var key = item[keyname];
                    if (authKeys.indexOf(key) === -1) {
                        authKeys.push(key);
                        authArr.push(item);
                    }
                });
            }
            return authArr;
        }
    }

    $rootScope.go = function (path) {
        publicmethod.go(path);
    };
    //设备宽高
    $rootScope.deviceInfo = {
        width: parseInt($window.innerWidth),
        height: parseInt($window.innerHeight),
        immerse: false
    }
    //注册app返回事件
    uranusPlus.backhandler = function () {
        $timeout(function () {
            if ($rootScope.Template.backlink) {
                publicmethod.go($rootScope.Template.backlink);
            } else {
                publicmethod.go('back');
            }
        }, 0);
    };

    var privatemethod = {
        // 把source的属性赋值到前面
        extend: function (destination, source) {
            for (var property in source) {
                destination[property] = source[property];
            }
        },
        div_process: null,
        div_process_bg: null,
        div_process_now: null,
        isLoding: false,
        currdom: 100,
        initloaddom: function () {
            //初始化数据 
            privatemethod.div_process = document.createElement('div');
            privatemethod.div_process.className = "div_process";
            privatemethod.div_process.setAttribute("id", "div_process");
            privatemethod.div_process.style.height = "2px";
            //背景进度条
            privatemethod.div_process_bg = document.createElement('div');
            privatemethod.div_process_bg.className = "loading-process-total";
            //进度条
            privatemethod.div_process_now = document.createElement("div");
            privatemethod.div_process_now.className = "loading-process";
            privatemethod.div_process_bg.appendChild(privatemethod.div_process_now);
            privatemethod.div_process.appendChild(privatemethod.div_process_bg);
            document.body.appendChild(privatemethod.div_process);
            privatemethod.div_process = document.querySelector(".loading-process");
        },
        loadingHandler: function (min, max, element) {
            if (privatemethod.isLoding) {
                privatemethod.currdom = min - 1;
                while (privatemethod.currdom < min || privatemethod.currdom > max || privatemethod.currdom > min * 3) {
                    privatemethod.currdom = Math.floor(Math.random() * max);
                }
                element.style.width = privatemethod.currdom + "%";
                setTimeout(function () {
                    if (privatemethod.currdom + 5 < max) {
                        privatemethod.loadingHandler(privatemethod.currdom, max, element);
                    }
                }, 200);
            }
        }
    }
    var initData = function () {
        /* 苹果手机加动画 */
        // if (publicmethod.versions.ios || publicmethod.versions.pad) {
        //     isanimate = true;
        //     var angular_body = angular.element(document.getElementsByTagName("body")[0]);
        //     if (!angular_body.hasClass("ios")) {
        //         angular_body.addClass("ios");
        //     }
        // }
        isanimate = true;
        var angular_body = angular.element(document.getElementsByTagName("body")[0]);
        if (!angular_body.hasClass("ios")) {
            angular_body.addClass("ios");
        }
        //app的状态栏的问题 
        uranusPlus.init(function () {
            if (uranusPlus.isIos()) {
                plus.runtime.setBadgeNumber(0);
            }
            var angular_body = angular.element(document.getElementsByTagName("body")[0]);
            if (!angular_body.hasClass("app")) {
                angular_body.addClass("app");
            }
            // if (plus.navigator.isImmersedStatusbar()) {
            //     $rootScope.deviceInfo.immerse = plus.navigator.isImmersedStatusbar();
            //     if (!angular_body.hasClass("immerse")) {
            //         angular_body.addClass("immerse");
            //     }
            // }

        });
    }

    /*------------------推广开始----------------------*/
    /*获取SourceTypeId的值*/
    function getMySourceTypeId() {
        var result = CacheFactory.getSourceTypeId() || localStorage.getItem("sourcetypeid");
        if ((result == null || result == " " || result == undefined)) {
            result = 100;
        }
        return result;
    }
    /*------------------推广结束----------------------*/

    privatemethod.initloaddom();
    initData();
    return publicmethod;
}]);